<template>
  <!-- 左侧组件 -->
  <el-scrollbar class="components-scrollbar">
    <el-collapse v-model="activeNames" class="components-list">
      <el-collapse-item
        :title="item.title"
        v-for="(item, index) in leftComponents"
        :key="index"
        :name="index"
      >
        <template slot="title">
          <div class="components-title">
            <svg-icon icon-class="component" />
            {{ item.title }}
          </div>
        </template>
        <draggable
          class="components-draggable"
          :list="item.list"
          :group="{ name: 'componentsGroup', pull: 'clone', put: false }"
          :clone="cloneComponent"
          draggable=".components-item"
          :sort="false"
          @end="onEnd"
        >
          <div
            v-for="(element, index) in item.list"
            :key="index"
            class="components-item"
            @click="addComponent(element)"
          >
            <div class="components-body">
              <svg-icon :icon-class="element.__config__.tagIcon" />
              {{ element.__config__.label }}
            </div>
          </div>
        </draggable>
      </el-collapse-item>
    </el-collapse>
  </el-scrollbar>
</template>

<script>
import draggable from "vuedraggable";
import { deepClone } from "../utils/index";

import {
  inputComponents,
  selectComponents,
  layoutComponents
} from "../utils/config";
import { createFormItem } from "../utils/index";
export default {
  components: {
    draggable
  },
  props: {
    // 表单属性
    formConf: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      activeNames: [0, 1, 2],
      leftComponents: [
        { title: "输入型组件", list: inputComponents },
        { title: "选择型组件", list: selectComponents },
        { title: "布局型组件", list: layoutComponents }
      ],
      tempActiveData: {} // 当前进行拖拽的组件
    };
  },
  methods: {
    // 拖拽完成
    onEnd(obj) {
      // from 拖拽开始组件，to 拖拽结束组件
      if (obj.from !== obj.to) {
        // 判断是否为动态数据，即 dataType === "dynamic",选择动态数据需要进行处理
        // this.fetchData(this.tempActiveData);
        this.$emit("drag", this.tempActiveData);
      }
    },
    addComponent(item) {
      const clone = this.cloneComponent(item);
      // this.fetchData(clone);
      // this.drawingList.push(clone);
      // 直接通过点击控件添加表单项，点击控件需要手动添加
      this.$emit("add", clone);
    },
    // 对控件进行拖拽，拖拽会自动添加控件，无须手动添加
    cloneComponent(origin) {
      const clone = deepClone(origin); // 对选中的控件进行深度克隆
      const config = clone.__config__;
      config.span = this.formConf.span || config.span; // 生成代码时，会根据span做精简判断
      // 给需要添加的控件添加自定义属性,即补充完整属性
      createFormItem(clone);
      clone.placeholder !== undefined && clone.placeholder;
      this.tempActiveData = clone; // 当前进行拖拽的组件
      return clone;
    }
  }
};
</script>

<style lang="scss"></style>
